<template>
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60vw">
    <!-- 列表 -->
    <ContentWrap>
      <el-table border :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }" :tree-props="treeProps"
        max-height="500" default-expand-all v-loading="loading" :data="list" row-key="id"
        @selection-change="handleRowCheckboxChange">
        <el-table-column type="selection" width="55" fixed :selectable="isRowSelectable" />
        <el-table-column prop="name" label="区域名称" />
        <el-table-column prop="leader" label="负责人">
          <template #default="scope">
            {{userList.find((user) => user.id === scope.row.leaderUserId)?.nickname}}
          </template>
        </el-table-column>
      </el-table>
    </ContentWrap>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { AuditAreaApi, AuditArea } from '@/api/business/auditarea'
import { handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'

/** 分层审核区域设置 表单 */
defineOptions({ name: 'AuditAreaForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
const loading = ref(true) // 列表的加载中
const list = ref() // 列表的数据

const treeProps = reactive({
  checkStrictly: true,
})

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deptId: undefined,
  dutyUserId: undefined,
  parentDeptId: undefined
})
const formRules = reactive({

})
const formRef = ref() // 表单 Ref

const bindDept = ref([])

const isRowSelectable = (row, index) => {
  // 如果 row.id 在 bindDept 数组中存在，则禁用（返回 false）
  return !bindDept.value.includes(row.id)

}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  //获取已存在的部门

  bindDept.value = await AuditAreaApi.getAuditAreaDeptIds()

  // 获取用户列表
  userList.value = await UserApi.getSimpleUserList()
  //获取部门
  await getList()


  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AuditAreaApi.getAuditArea(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 查询部门列表 */
const getList = async () => {
  loading.value = true
  let params = {
    bindIds: bindDept.value ?? []
  }
  try {
    const data = await DeptApi.getDeptListUnbind(params)
    list.value = handleTree(data)
  } finally {
    loading.value = false
  }
}

/** 批量删除按钮操作 */
const checkedIds = ref([])
const handleRowCheckboxChange = (rows) => {
  checkedIds.value = rows.map((row) => row)
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {

  console.log("checkedIds", checkedIds.value);

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AuditArea

    let params = {
      deptList: checkedIds.value
    }

    if (formType.value === 'create') {
      await AuditAreaApi.createAuditArea(params)
      message.success(t('common.createSuccess'))
    } else {
      await AuditAreaApi.updateAuditArea(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deptId: undefined,
    dutyUserId: undefined,
    parentDeptId: undefined
  }
  formRef.value?.resetFields()
}
</script>
